<template>
  <TopNavBar :title="_t18('19_order_detail')" type="back" />
  <div class="nav-space"></div>

  <div class="order-detail-card" v-if="order">
    <div class="header">
      <span class="pair">{{ order.coinSymbol?.toUpperCase() }}/USDT</span>
	    <!-- ✅ 倒计时显示 -->
	    <span
	      v-if="order.status == 0 && countdown > 0"
	      class="countdown1"
	      :class="flashMode"
	    >
	      <!--{{ countdown }}s-->
	    </span>

      <div v-if="order.status == 3" class="status settle">{{ _t18('21_pending_settle') }}</div>
      <div v-if="order.status == 0" class="status holding">{{ _t18('19_holding') }}</div>
      <div v-if="order.status == 1" class="status success">{{ _t18('19_completed') }}</div>
      <div v-if="order.status == 2" class="status cancel">{{ _t18('19_canceled') }}</div>
    </div>

    <div class="order-id" @click="copyOrderNo">
      {{ order.orderNo }}
    </div>

    <!-- AI 订单 (多交易所) -->
    <template v-if="order.aiType == '2'">
      <div class="row">
        <span>{{ _t18('19_open_time') }}</span>
      <span>{{ convertBeijingToZone12(order.openTime, order.timeZone) }}</span>
      </div>

      <div class="row">
        <div>
          <img class="icon" :src="order.buy?.icon" />
          <span>{{ order.buy?.exchangeName }}{{ _t18('19_price') }}</span>
        </div>
        <span>{{ (Number(order.openPrice) + Number(order.buy?.spread)).toFixed(5) }} $</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_action') }}</span>
        <span :class="order.betContent == '0' ? 'fall' : 'rise'">
          {{ order.betContent == '0' ? _t18('19_fall') : _t18('19_rise') }}
        </span>
      </div>

      <div class="row">
        <span>{{ _t18('19_duration') }}</span>
        <span>{{ order.type }}{{ _t18('19_seconds') }}</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_profit_rate') }}</span>
        <span class="profit">{{ (order.rate * 100).toFixed(0) }}%</span>
      </div>

      <div class="row">
        <div>
          <img class="icon" :src="order.sell?.icon" />
          <span>{{ order.sell?.exchangeName }}{{ _t18('19_price') }}</span>
        </div>
        <span v-if="order.status == 3 || order.status == 0" class="settle-text">{{ _t18('21_settling') }}</span>
        <span v-else>{{ (Number(order.closePrice) + Number(order.sell?.spread)).toFixed(5) }} $</span>
      </div>


      <div class="row">
        <span>{{ _t18('19_profit') }}</span>
        <span v-if="order.status == 3 || order.status == 0" class="settle-text">{{ _t18('21_settling') }}</span>
        <span
          v-else
          class="profit"
          :style="{ color: order.rewardAmount > 0 ? '#03b303' : '#f10430' }"
        >
          {{ order.rewardAmount > 0 ? '+' : '-' }}
          {{ Math.abs(order.rewardAmount || order.betAmount) }} USD
        </span>
      </div>
	  
	  <!-- ✅ 订单详情倒计时（参考历史订单样式） -->
	  <div
	    v-if="order.status == 0 || order.status == 3"
	    class="detail-countdown-line"
	  >
	    <div class="detail-countdown-card-wrap">
	      <div v-if="formatCountdownDetail(order).show.includes('d')" class="detail-count-card gray">
	        <div class="num">{{ formatCountdownDetail(order).days }}</div>
	        <div class="label">{{ _t18('day') }}</div>
	      </div>
	      <div v-if="formatCountdownDetail(order).show.includes('h')" class="detail-count-card red">
	        <div class="num">{{ formatCountdownDetail(order).hours }}</div>
	        <div class="label">{{ _t18('hour') }}</div>
	      </div>
	      <div v-if="formatCountdownDetail(order).show.includes('m')" class="detail-count-card green">
	        <div class="num">{{ formatCountdownDetail(order).minutes }}</div>
	        <div class="label">{{ _t18('minute') }}</div>
	      </div>
	      <div v-if="formatCountdownDetail(order).show.includes('s')" class="detail-count-card yellow">
	        <div class="num">{{ formatCountdownDetail(order).seconds }}</div>
	        <div class="label">{{ _t18('second') }}</div>
	      </div>
	    </div>
	  </div>


    </template>

    <!-- 普通订单 (单交易所，aiType == '1') -->
    <template v-if="order.aiType == '1'">
      <div class="row">
        <span>{{ _t18('19_open_time') }}</span>
        <span class="value">{{ convertBeijingToZone(order.openTime, order.timeZone) }}</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_open_price') }}</span>
        <span class="value">{{ Number(order.openPrice).toFixed(4) }} USD</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_action') }}</span>
        <span class="value" :class="order.betContent == '1' ? 'rise' : 'fall'">
          {{ order.betContent == '1' ? _t18('19_rise_detail') : _t18('19_fall_detail') }}
        </span>
      </div>

      <div class="row">
        <span>{{ _t18('19_duration') }}</span>
        <span class="value">{{ order.type == 60 ? _t18('19_one_min') : order.type + _t18('19_seconds') }}</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_profit_rate') }}</span>
        <span class="value green">{{ (order.rate * 100).toFixed(0) }}%</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_close_price') }}</span>
        <span v-if="order.status == 3" class="settle-text">{{ _t18('21_settling') }}</span>
        <span v-else class="value">{{ Number(order.closePrice).toFixed(4) }} USD</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_buy_amount') }}</span>
        <span class="value">{{ order.betAmount }} USD</span>
      </div>

      <div class="row">
        <span>{{ _t18('19_profit') }}</span>
        <span v-if="order.status == 3" class="settle-text">{{ _t18('21_settling') }}</span>
        <span v-else class="value" :class="order.rewardAmount > 0 ? 'green' : 'red'">
          {{ order.rewardAmount > 0 ? '+' : '-' }}
          {{ Math.abs(order.rewardAmount || order.betAmount).toFixed(4) }} USD
        </span>
      </div>

      <div class="row">
        <span>{{ _t18('19_fee') }}</span>
        <span class="value">0 USD</span>
      </div>
    </template>
  </div>

  <div v-else class="empty-detail">{{ _t18('19_order_not_found') }}</div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { secondContractOrderselectOrderList } from '@/api/trade/index'
import { getContractListApi } from '@/api/ai/index'
import { _t18, _beijingToLocal, convertBeijingToZone } from '@/utils/public'
import { showToast } from 'vant'
// ✅ 12小时制时间转换（带 AM / PM）
function convertBeijingToZone12(time, timeZone) {
  const timeStr = convertBeijingToZone(time, timeZone)
  if (!timeStr) return '-'

  const match = timeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2}):(\d{2})/)
  if (!match) return timeStr

  const [, y, m, d, h, min, s] = match
  const hour = parseInt(h, 10)
  const ampm = hour >= 12 ? 'PM' : 'AM'
  const displayHour = hour % 12 === 0 ? 12 : hour % 12

  return `${y}-${m}-${d} ${displayHour}:${min}:${s} ${ampm}`
}

const route = useRoute()
const orderId = ref(route.query.id)
const order = ref({})
const exchanges = ref([])
const countdown = ref(0)
const flashMode = ref('normal') // ✅ 补上这个，默认正常模式
const timer = ref(null)

const initExchanges = async () => {
  const res = await getContractListApi()
  if (res.code === 200) return res.data
  return []
}

const getList = async () => {
  try {
    const data = await initExchanges()
    exchanges.value = data
    const res = await secondContractOrderselectOrderList({ id: orderId.value })
    if (res.code == 200 && res.data.length) {
      order.value = res.data[0]
      order.value.buy = exchanges.value.find(ex => Number(ex.id) == Number(order.value.buyPlat))
      order.value.sell = exchanges.value.find(ex => Number(ex.id) == Number(order.value.sellPlat))
    
      // ✅ 数据加载完成后启动倒计时
      startCountdown()
    }
  } catch (error) {
    console.error(error)
  }
}

// ✅ 倒计时逻辑
function startCountdown() {
  if (!order.value.openTime || !order.value.type) return
  const start = new Date(order.value.openTime).getTime()
  const duration = order.value.type * 1000
  clearInterval(timer.value)

  timer.value = setInterval(() => {
    const remain = Math.max(0, (start + duration - Date.now()) / 1000)
    countdown.value = Math.floor(remain)

    // ✅ 根据进度设置闪烁模式
    const progress = 1 - remain / (duration / 1000)
    if (progress < 0.7) flashMode.value = 'normal'
    else flashMode.value = 'fast'

    // ✅ 到期自动刷新
    if (remain <= 0) {
      clearInterval(timer.value)
      setTimeout(() => getList(), 500)
    }
  }, 1000)
}


function formatCountdownDetail(order) {
  if (!order.openTime || !order.type) {
    return { days: '00', hours: '00', minutes: '00', seconds: '00', show: ['s'] }
  }

  const start = new Date(order.openTime).getTime()
  const end = start + order.type * 1000
  const now = Date.now()
  let remain = Math.max(0, (end - now) / 1000)

  const days = Math.floor(remain / 86400)
  remain %= 86400
  const hours = Math.floor(remain / 3600)
  remain %= 3600
  const minutes = Math.floor(remain / 60)
  const seconds = Math.floor(remain % 60)

  let show = []
  if (days > 0) show = ['d', 'h', 'm', 's']
  else if (hours > 0) show = ['h', 'm', 's']
  else if (minutes > 0) show = ['m', 's']
  else show = ['s']

  return {
    days: days.toString().padStart(2, '0'),
    hours: hours.toString().padStart(2, '0'),
    minutes: minutes.toString().padStart(2, '0'),
    seconds: seconds.toString().padStart(2, '0'),
    show
  }
}

/** ✅ 复制订单号函数 */
const copySuccessText = _t18('copy_success')
const copyFailText = _t18('copy_fail')

function copyOrderNo() {
  if (!order.value?.orderNo) return

  navigator.clipboard
    .writeText(order.value.orderNo)
    .then(() => {
      showToast({
        message: copySuccessText,
        position: 'bottom',
        duration: 1500
      })
    })
    .catch(() => {
      showToast({
        message: copyFailText,
        position: 'bottom',
        duration: 1500
      })
    })
}






onMounted(() => getList())
onUnmounted(() => clearInterval(timer.value))
</script>

<style scoped>
.nav-space {
  height: 20px;
}

.order-detail-card {
  background: #fff;
  border-radius: 10px;
  padding: 28px 26px;
  margin: 0 auto 40px;
  max-width: 380px;
  width: calc(100% - 40px);
  box-shadow: 0 4px 14px 0 rgba(0, 0, 0, 0.05);
}

@media (max-width: 480px) {
  .order-detail-card {
    width: calc(100% - 30px);
    padding: 24px 20px;
  }

  .nav-space {
    height: 15px;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.pair {
  font-size: 20px;
  font-weight: 700;
}

.status.success {
  color: #00c853;
  font-weight: 600;
}

.status.holding {
  color: #ff9800;
  font-weight: 600;
}

.order-id {
  color: #888;
  font-size: 13px;
  margin-bottom: 20px;
  word-break: break-all;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 14px 0;
  font-size: 15px;
}

.value {
  font-weight: 600;
  color: #000;
}

.green {
  color: #03b303;
}

.red {
  color: #f10430;
}

.rise {
  color: #03b303;
  font-weight: 600;
}

.fall {
  color: #f10430;
  font-weight: 600;
}

/* 结算中：去掉斜体，保持灰色 */
.settle-text {
  color: #999;
  font-weight: 500;
  /* 去掉 font-style: italic; */
}

.icon {
  width: 20px;
  height: 20px;
  margin-right: 6px;
}

.empty-detail {
  text-align: center;
  color: #888;
  margin-top: 80px;
  font-size: 18px;
}
.status {
  font-weight: 600;
}

/* 结算中 */
.status.settle {
  color: #ff9800;
}

/* 持仓中 */
.status.holding {
  color: #f10430;
}

/* 已完成 */
.status.success {
  color: #03b303;
}

/* 已撤单 */
.status.cancel {
  color: #999;
}
/* 看涨=绿色，看跌=红色（仅补样式，不动模板） */
.active {
  color: #03b303;
  font-weight: 600;
}
.active1 {
  color: #f10430;
  font-weight: 600;
}
/* ✅ 历史订单同款倒计时样式 */
.countdown {
  font-size: 14px;
  font-weight: 600;
  color: #03b303;
  margin-left: 4px;              /* ✅ 轻微间距 */
  display: inline-flex;
  align-items: baseline;         /* ✅ 与 BTC/USDT 基线对齐 */
  line-height: 1;
  transform: translateY(1px);    /* ✅ 微调下沉对齐感 */
  opacity: 0.95;
  transition: color 0.3s ease, opacity 0.3s ease;
}

/* ✅ 前 70% 平稳绿色，后 30% 转橙红并柔和呼吸 */
.countdown.normal {
  color: #03b303;
}

.countdown.fast {
  color: #fa190c;
  animation: countdownPulse 1.2s ease-in-out infinite;
}

@keyframes countdownPulse {
  0% {
    opacity: 0.7;
    transform: translateY(1px) scale(0.97);
  }
  50% {
    opacity: 1;
    transform: translateY(1px) scale(1.03);
  }
  100% {
    opacity: 0.8;
    transform: translateY(1px) scale(0.98);
  }
}
/* ✅ 订单详情页倒计时样式（继承历史订单样式） */
.detail-countdown-line {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.detail-countdown-card-wrap {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

.detail-count-card {
  width: 42px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.25),
              inset 0 -1px 2px rgba(255, 255, 255, 0.15);
  background: linear-gradient(180deg, #2a2a2a, #111);
  transition: all 0.3s ease;
}

.detail-count-card .num {
  font-size: 16px;
  font-weight: 800;
  font-family: 'Courier New', Courier, monospace;
}

.detail-count-card .label {
  font-size: 9px;
  opacity: 0.9;
  font-weight: 600;
  margin-top: 4px;
  text-transform: uppercase;
}

.detail-count-card.gray {
  background: linear-gradient(180deg, #9e9e9e, #5c5c5c);
  color: #fff;
}
.detail-count-card.red {
  background: linear-gradient(180deg, #f44336, #b71c1c);
  color: #fff;
}
.detail-count-card.green {
  background: linear-gradient(180deg, #4caf50, #1b5e20);
  color: #fff;
}
.detail-count-card.yellow {
  background: linear-gradient(180deg, #ffca28, #ff9800);
  color: #222;
}




</style>
